package com.treasure.web.listener;

import com.treasure.common.utils.InetUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * @author sunhongmin
 * @date 2023/10/14 15:25
 * @description
 */
@Component
@Slf4j
public class ApplicationStartListener implements ApplicationListener<ApplicationStartedEvent>, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(@NotNull ApplicationStartedEvent applicationStartedEvent) {
        InetAddress localAddress = InetUtils.getLocalAddress();
        String localIP = localAddress == null ? "" : localAddress.getHostAddress();
        Environment environment = applicationContext.getBean(Environment.class);
        String applicationName = environment.getProperty("spring.application.name");
        String msg = applicationName + "服务启动成功，IP：" + localIP + "，环境：" + getActiveProfile();
        log.info(msg);
    }

    public String getActiveProfile() {
        String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
        if (!ArrayUtils.isEmpty(profiles)) {
            return profiles[0];
        }
        return "";
    }

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
